﻿using System;

namespace TK
{
    public partial class CustomSerializer
    {     
        void writeArray(CustomSerializerState state, Array o)
        {
            var objID = state.writeHeader();
            state.writeInt32(o.Length);
            var elementType = o.GetType().GetElementType();
            state.writeTypeName(elementType);
            writeSingleTypeCollection(state, o, elementType);
            state.updateHeader(objID);
        }

        object readArray(CustomSerializerState state, Type expectedElementType, Type ownerType, string propertyName) {
            var header = state.readHeader();
            var length = state.readInt32();
            var storedElementType = getTypeByName(state.readTypeName(), state.settings.ClassMap);

            var o = Array.CreateInstance(storedElementType, length);
            readSingleTypeCollection(state, o, storedElementType, ownerType, propertyName);

            if (expectedElementType != null && expectedElementType != storedElementType)
                return convertArray(o, expectedElementType, ownerType, propertyName);
            return o;
        }
    }
}